#include "Widget.h"
#include "ui_Widget.h"
#include <QDateTime>
#include <QDebug>
#include <QMovie>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    /* 取消边框 */
    this->setWindowFlags(Qt::FramelessWindowHint);

    /* 设置欢迎动画 */
    QMovie *movie = new QMovie(":/welcome.gif");
    ui->WelcomeBackgroung->setMovie(movie);
    movie->start();

    /* 初始化管理类 */
    this->man = new Management;

    this->updateUI();

    /* 初始化Tcp服务器 */
    this->Server = new QTcpServer;
    this->ServerCamera = new QTcpServer;

    /* 初始化套接字 */
    this->Socket = new QTcpSocket;
    this->SocketCamera = new QTcpSocket;

    /* 监听任意主机 */
    this->Server->listen(QHostAddress::Any, PORT);
    this->ServerCamera->listen(QHostAddress::Any, CAMERA_PORT);

    //this->thread = new myThread(this);

#if 0
    this->man->getEmptySpace();
    this->man->getEmptySpace();
    this->man->getEmptySpace();
    qDebug() << "===================" << endl;
    //this->man->FreeParkingSpace(1);
    //this->man->FreeParkingSpace(2);
    this->man->FreeParkingSpace(3);
    this->updateUI();

    Car newCar = this->man->QueryCarFromDatabase("车牌号");
    newCar.setCost(PRICE);
    qDebug() << newCar.getCost();
#endif

    /* 关联接收连接槽函数 */
    this->connect(Server, SIGNAL(newConnection()),this, SLOT(connectSlot()));
    this->connect(ServerCamera, SIGNAL(newConnection()),this, SLOT(connectCameraSlot()));


}

Widget::~Widget()
{
    delete ui;
    delete this->Server;
    delete this->ServerCamera;
    delete this->Socket;
    delete this->SocketCamera;
    delete this->man;

}

void Widget::connectSlot()
{
    while (this->Server->hasPendingConnections()) {

        /* 启动线程 */
        //this->thread->start();
        this->Socket = this->Server->nextPendingConnection();
        ui->Show->setText("New connected! IP:" + this->Socket->peerAddress().toString());
        this->sendInfo(SHOW,"Number of remainning parking space：" + QString::number(this->man->getEmptySpaceNum()));
        this->connect(this->Socket, SIGNAL(readyRead()), this, SLOT(recvInfoSlot()));
    }
}

void Widget::connectCameraSlot()
{
    qDebug() << "123" << endl;
    while (this->ServerCamera->hasPendingConnections()) {

        /* 启动线程 */
        //this->thread->start();
        this->SocketCamera = this->ServerCamera->nextPendingConnection();
        //ui->Show->setText("New connected! IP:" + this->Socket->peerAddress().toString());
        //this->sendInfo(SHOW,"Number of remainning parking space：" + QString::number(this->man->getEmptySpaceNum()));
        this->connect(this->SocketCamera, SIGNAL(readyRead()), this, SLOT(recvCameraInfoSlot()));
    }
}

void Widget::recvInfoSlot()
{
    /* 读取所有数据 */
    QString str = this->Socket->readAll();
    qDebug() << str << endl;

    /* 截取字符串 */
    QStringList list = str.split(":");

    /* 获取命令 */
    QString cmd = list.at(0);
    qDebug() << "命令:" << cmd << endl;

    /* 获取数据 */
    QString data = list.at(1);
    qDebug() << "数据:" << data << endl;

    /* 错误判断 */
    bool ok;
    u_long num = cmd.toInt(&ok);
    if (!ok) {
        qDebug() << "命令错误!!" << endl;
        return;
    }
    switch (num) {

    /* 登录 */
    case LOGIN:
    {
        qDebug() << "登录..." << endl;
        QStringList s = data.split(" ");
        QString PhoneNumStr = s.at(0);
        QString PasswordStr = s.at(1);
        bool ok;
        Usr usr = this->man->QueryUsrFromDatabase(PhoneNumStr, &ok);
        if (!ok) {

            /* 未找到用户 */
            this->sendInfo(NOT_FOUNT_USR);
            qDebug() << "未找到用户!" << endl;
            break;

        }
        if (usr.getPassword() == PasswordStr) {

            /* 登录成功 */
            this->sendInfo(LOGIN_OK);
            qDebug() << "登录成功!" << endl;
            break;
        }

        /* 密码错误 */
        this->sendInfo(PASSWORD_ERR);
        qDebug() << "密码错误!" << endl;
    }break;

    /* 注册 */
    case JOIN:
    {
        qDebug() << "注册..." << endl;
        QStringList s = data.split(" ");
        QString UsrNameStr  = s.at(0);
        QString PhoneNumStr = s.at(1);
        QString PasswordStr = s.at(2);

        Usr usr(UsrNameStr);
        usr.setPhoneNum(PhoneNumStr);
        usr.setPassword(PasswordStr);
        this->man->AddUsrToDatabase(usr);

        this->sendInfo(JOIN_OK);
        qDebug() << "注册成功" << endl;

    }break;

    /* 预约 */
    case RESERVATION:
    {
        /* 测试时是停车功能 */
        qDebug() << "预约..." << endl;
        /* 设置预约车辆 */
        Car newCar(data);
        newCar.setReservation(true);
#if 0
        //临时测试功能
        newCar.setEntryTime(QDateTime::currentDateTime());
#endif
        this->man->setCar(newCar);

        /* 获取空车位 */
        u_long num = this->man->getEmptySpace();
        if (0 == num) {
            qDebug() << "没有空车位!" << endl;
            this->sendInfo(RESERVATION_ERR, "No empty parking space!");
            break;
        }

        /* 设置车位号 */
        newCar.setParkingNum(num);

        /* 将预约车辆添加到数据库 */
        this->man->AddCarToDatabase(newCar);

        /* 更新ui */
        this->updateUI();

        this->sendInfo(SHOW,"Number of remainning parking space " + QString::number(this->man->getEmptySpaceNum()));

        /* 发送数据到客户端,发送车位号 */
        this->sendInfo(RESERVATION_OK, "Pleace park in parking space number " + QString::number(num));
        qDebug() << "预约成功!" << endl;
    }break;

    /* 支付 */
    case PAY:
    {
        qDebug() << "支付" << endl;
        Car newCar = this->man->getCar();
        newCar.setPaymentStatus(true);
        this->man->UpdateCarFromDatabase(newCar);
        this->sendInfo(PAY_OK);
    }break;
    /* 注销 */
    case DELETE_USR:
    {
        qDebug() << "注销" << endl;
        this->man->DeleteUsrFromDatabase(data);
        this->sendInfo(DELETE_USR_OK);
    }break;
    /* 取车 */
    case PICK_CAR:
    {
        qDebug() << "取车..." << endl;
        Car delCar = this->man->QueryCarFromDatabase(data);
        delCar.setLeaveTime(QDateTime::currentDateTime());
        delCar.setParkingTime();
        delCar.setCost(PRICE);
        this->man->setCar(delCar);
        qDebug() << "ParkingNum:" << delCar.getParkingNum() << endl;
        this->man->FreeParkingSpace(delCar.getParkingNum());
        this->updateUI();
        this->man->DeleteCarFromDatabase(delCar.getCarNum());
        double cost = this->man->getCar().getCost();
        this->sendInfo(PICK_CAR_OK,"Please pay " + (cost ? QString::number(cost) : "0") + "yuan.");
        this->sendInfo(SHOW,"Number of remainning parking space " + QString::number(this->man->getEmptySpaceNum()));
        qDebug() << "取车成功!" << endl;
    }break;

    default:
        qDebug() << "未知命令!" << endl;
        break;
    }

}

void Widget::recvCameraInfoSlot()
{
    /* 读取所有数据 */
    QString str = this->SocketCamera->readAll();
    qDebug() << str << endl;
    if ( "unknow" == str) {
        qDebug() << "未知！" << endl;
        return;
    }

    /* 截取字符串 */
    QStringList list = str.split(":");
    if (-1 == str.indexOf(":")) {
        return;
    }

    /* 获取命令 */
    QString cmd = list.at(0);
    qDebug() << "颜色:" << cmd << endl;

    /* 获取数据 */
    QString data = list.at(1);
    if (data.isEmpty()) {
        return;
    }
    QStringList Value = data.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
    data = Value.at(0);
    if (data.isEmpty()) {
        return;
    }
    qDebug() << "车牌号:" << data << endl;

    bool ok;
    Car newCar = this->man->QueryCarFromDatabase(data,&ok);

    /* 预约车辆 */
    if (ok) {
        /* 进入 */
        qDebug() << "停车..." << endl;
        if ("-" == newCar.getEntryTime()) {
            newCar.setEntryTime(QDateTime::currentDateTime());
            this->man->UpdateCarFromDatabase(newCar);
            qDebug() << "停车成功!" << endl;
        }
        /* 离开 */
        else {
            newCar.setLeaveTime(QDateTime::currentDateTime());
            this->man->UpdateCarFromDatabase(newCar);
            newCar.setParkingTime();
            newCar.setCost(PRICE);
            this->man->setCar(newCar);
            qDebug() << "ParkingNum:" << newCar.getParkingNum() << endl;
            this->man->FreeParkingSpace(newCar.getParkingNum());
            this->updateUI();
            this->man->DeleteCarFromDatabase(newCar.getCarNum());
            double cost = this->man->getCar().getCost();
            this->sendInfo(PICK_CAR_OK,"Please pay " + (cost ? QString::number(cost) : "0") + "yuan.");
            this->sendInfo(SHOW,"Number of remainning parking space " + QString::number(this->man->getEmptySpaceNum()));
            qDebug() << "取车成功!" << endl;
        }
    }
    /* 非预约车辆 */
    else {
        newCar.setCarNum(data);
        newCar.setEntryTime(QDateTime::currentDateTime());

        /* 获取空车位 */
        u_long num = this->man->getEmptySpace();
        if (0 == num) {
            qDebug() << "没有空车位!" << endl;
            return;
        }

        /* 设置车位号 */
        newCar.setParkingNum(num);

        this->man->AddCarToDatabase(newCar);
        this->man->setCar(newCar);
        this->updateUI();
    }
}

Management *Widget::getMan() const
{
    return man;
}

QTcpServer *Widget::getServer() const
{
    return Server;
}

void Widget::sendInfo(int cmd, const QString &data)
{
    QString str = QString::number(cmd);
    str += ":";
    str += data;
    this->Socket->write(str.toUtf8());
}

void Widget::updateUI()
{
    /* ui界面显示 */
    ui->EmptySpaceNum->display((int)this->man->getEmptySpaceNum());
    ui->CarNum->setText(man->getCar().getCarNum());
    ui->Cost->setText(man->getCar().getCost() < 0 ? "-" : QString::number(man->getCar().getCost()));
    ui->EntryTime->setText(man->getCar().getEntryTime());
    ui->LeaveTime->setText(man->getCar().getLeaveTime());
    ui->ParkingTime->setText(man->getCar().getParkingTime());
    ui->PaymentStatus->setText(man->getCar().getPaymentStatus() ? "Paid" : "Unpaid");

    this->update();
}
